<template>
  <!-- 推送记录 -->
  <div class="app-container">
    <el-form class="search-form-new" :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品编号" prop="accountid">
        <el-input v-model="queryParams.accountid" placeholder="请输入商品编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="渠道" prop="salecode">
        <el-select clearable filterable v-model="queryParams.salecode" placeholder="请选择渠道">
          <el-option v-for="dict in saleList" :key="dict.id" :label="dict.name" :value="dict.saleName" />
        </el-select>
      </el-form-item>
      <el-form-item label="游戏" prop="type">
        <el-select filterable v-model="queryParams.type" placeholder="请选择游戏" clearable>
          <el-option v-for="dict in allGameList" :key="dict.id" :label="dict.name" :value="dict.name" />
        </el-select>
      </el-form-item>
      <el-form-item label="操作类型" prop="inter">
        <el-select clearable filterable v-model="queryParams.inter" placeholder="请选择操作类型">
          <el-option v-for="dict in statusList" :key="dict" :label="dict" :value="dict" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="状态" prop="successCount">
        <el-select clearable filterable v-model="queryParams.successCount" placeholder="请选择状态">
          <el-option v-for="dict in sucessList" :key="dict.id" :label="dict.status" :value="dict.id" />
        </el-select>
      </el-form-item>
      <el-form-item class="btns">
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button type="warning" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        <!-- <el-button v-hasPermi="['add:price:remove']" type="danger" plain icon="el-icon-delete" :loading="exportLoading" @click="rmRec">一键重推</el-button> -->
      </el-form-item>
    </el-form>
    <div class="table_box">
      <el-table  stripe border v-loading="loading" :data="recList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" width="100" prop="id" />
        <el-table-column label="渠道" prop="saleId" show-overflow-tooltip="" min-width="150"/>
        <el-table-column label="游戏" prop="type"/>
        <el-table-column label="商品编号" prop="accountid" />
        <el-table-column label="状态">
          <template slot-scope="scope">
            <div>
              <span v-show="scope.row.successCount=='1'" style="color:green">成功</span>
              <span v-show="scope.row.successCount=='0'" style="color:red">失败</span>
              <div v-if="scope.row.successCount=='0'">
                {{scope.row.resss}}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="接口类型">
          <template slot-scope="scope">
            <div>
              <span v-show="scope.row.inter=='add'" style="color:green">新增</span>
              <span v-show="scope.row.inter=='del'" style="color:red">删除</span>
              <span v-show="scope.row.inter=='edit'" style="color:orange">编辑</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="推送时间" prop="createTime" width="160"/>
        <el-table-column label="请求参数" prop="req">
          <template slot-scope="scope">
            <el-button type="text" @click="showReq(scope.row)">请求参数</el-button>
          </template>
        </el-table-column>
        <el-table-column label="响应参数" prop="req">
          <template slot-scope="scope">
            <el-button type="text" @click="showRes(scope.row)">响应参数</el-button>
          </template>
        </el-table-column>
        <!-- <el-table-column fixed="right" label="操作" width="120" v-hasPermi="['pushrec:repush']">
          <template slot-scope="scope">
            <el-button type="primary" @click="correctPush(scope.row)" plain>校正重推</el-button>
          </template>
        </el-table-column> -->
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    </div>

    <el-dialog title="参数" :visible.sync="showSinNumVisible" append-to-body>
      <span>{{ req }}</span>
    </el-dialog>
    <el-dialog title="删除记录" :visible.sync="rmRecVisible" append-to-body>
      <label for="">
        <SPAN>选择渠道：</SPAN>
        <el-select filterable v-model="delPartId" placeholder="请选择渠道" clearable>
          <el-option v-for="dict in saleList" :key="dict.id" :label="dict.name" :value="dict.saleName" />
        </el-select>
      </label>
      <div style="margin-top:15px"></div>
      <label for="">
        <SPAN>选择游戏：</SPAN>
        <el-select filterable v-model="delGameName" placeholder="请选择游戏" clearable>
          <el-option v-for="dict in allGameList" :key="dict.id" :label="dict.name" :value="dict.name" />
        </el-select>
      </label>

      <div class="tip">提示：该操作会将选中的渠道所有推送记录删掉，并重新推送所有符合规则的商品。请确保该操作前，已在对方平台全部下架或删除你的商品，否则会造成商品重复推送，导致失败！请谨慎操作！</div>
      <div slot="footer" class="dialog-footer">

        <el-button @click="rmRecVisible = false">取 消</el-button>
        <el-button type="primary" @click="rmRecSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listRec,
  getRec,
  delRec,
  addRec,
  updateRec,
  delRecNew,
  exportRec,
} from "@/api/info/rec";
import { delAcount, getInfo, updateInfo } from "@/api/info/info";
import { allList } from "@/api/partner/partner";
import { getDicts } from "@/api/system/dict/data";
export default {
  name: "Rec",
  data() {
    return {
      delPartId: "",
      delGameName: "",

      formAccount: {},
      dialogVisible: false,
      Accountopen: false,
      dialogGameType: "",
      dialogGameTypeHp: "",
      checkedSales: [],
      rmRecVisible: false,
      showSinNumVisible: false,
      statusList: ["add", "edit", "del"],
      sucessList: [
        { status: "成功", id: 1 },
        { status: "失败", id: 0 },
      ],
      saleList: [],
      // 遮罩层
      loading: true,
      req: "",
      imageUrl: "",
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 10000,
      // 推送记录表格数据
      recList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      configId: "",
      ifSpecial: true,
      regionalArr: [],
      levelArr: [],
      videoList: [],
      fileNameArr: [],
      imgFileList: [],
      dialogImageUrl: "",
      imgShowList: [], //传给后台的图片
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        createId: null,
        saleId: null,
        result: null,
        strCode: null,
        isSucess: null,
        inter: null,
        accountid: null,
        salecode: null,
        type:''
      },
      // 表单参数
      form: {},
      inter: "",
      // 表单校验
      rules: {},
    };
  },
  props: ["params"],
  created() {
    this.allSale();
  },
  watch: {
    params: {
      handler(newVal) {
        if (newVal) {
          this.queryParams.accountid = null;
          this.queryParams.salecode = null;
          if (newVal.accountId) this.queryParams.accountid = newVal.accountId;
          if (newVal.saleCode) this.queryParams.salecode = newVal.saleCode;
          this.getList();
        }
      },
      immediate: true,
      deep: true,
    },
    $route: {
      handler(val) {
        if (val.path == "/tenantUtils/rec/index") {
          if (val.query.salecode) {
            this.queryParams.salecode = val.query.salecode;
            this.getList();
          } else {
            this.queryParams.salecode = "";
            this.getList();
          }
        }
      },
      immediate: true,
      deep: true,
    },
  },
  computed: {
    allGameList() {
      return this.$store.getters.allGameList;
    },
  },
  methods: {
    submit() {
      this.$refs["formAccount"].validate((valid) => {
        if (valid) {
          if (this.inter == "编辑") {
            this.formAccount.interType = "edit";
          } else {
            this.formAccount.interType = "add";
          }
          const that = this;
          this.formAccount.configId = this.configId;
          this.formAccount.urlArr = this.imgFileList;

          updateInfo(this.formAccount).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.Accountopen = false;
            this.getList();
          });
        }
      });
    },

    selectLable(resultDate) {
      this.resultDate = resultDate;
    },
    handleRemove(response, fileList, file) {
      const that = this;
      // 1.获取将要删除图片的临时路径
      const filePath = response.url;

      // 2.找到图片对应的索引值
      this.imgFileList.forEach(function (element, keifSpecialy) {
        if (element.url === filePath) {
          that.imgFileList.splice(key, 1); //传给后台的图片
        }
      });
      console.log(this.imgFileList);
    },
    uploadNumber(file, fileList) {
      //限制图片数量
      this.$$modal.msgError("最多只能上传20张图片");
    },
    changeSpecial() {
      console.log(this.formAccount.accType);
      if (1 == this.formAccount.accType) {
        this.ifSpecial = false;
      } else {
        this.formAccount.specialPrice = null;
      }
    },
    closeDialog() {
      this.imgFileList = [];
      this.imgShowList = [];
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleAvatarRemove(response, file) {
      console.log(file);
      console.log(response);
    },
    handleAvatarSuccess(res, file) {
      console.log(file);
      console.log(res);
      // this.imageUrl = URL.createObjectURL(file.raw);
      this.formAccount.titleImg = res.data.filePath;
      this.imageUrl = res.data.filePath;
    },
    handleVideoSuccess(res, file) {
      if (res.code == 200) {
        this.formAccount.videoUrl = res.data.filePath;
        this.formAccount.videoName = res.data.fileName;
      }
    },
    handleVideoRemove(response, fileList, file) {
      this.formAccount.videoUrl = "";
      this.formAccount.videoName = "";
    },
    handleUploadSuccess(res, file) {
      if (res.code == 200) {
        let url = res.data.filePath;
        let name = res.data.fileName;
        let param = {};
        param.url = url;
        param.name = name;
        this.imgFileList.push(param);
        console.log(this.imgFileList);
      }
    },
    selectDialogGameType() {
      let gameType = this.formAccount.type;
      this.getSelectGameInfo(gameType);
    },
    getConfigId(saleName) {
      let params = {};
      params.name = saleName;
      params.status = 1;
      allList(params).then((res) => {
        if (res.code == 200) {
          if (res.rows.length > 0) {
            this.configId = res.rows[0].id;
          } else {
            this.configId = 0;
          }
        } else {
          this.$modal.msgError("请求失败");
        }
      });
    },
    getSelectGameInfo(gameType) {
      console.log(gameType);
      // byColums("level", gameType).then((res) => {
      //   console.log(res);
      //   if (res.code == 200) {
      //     this.levelArr = res.data;
      //   }
      // });
      getDicts(gameType + "段位").then((res) => {
        if (res.code == 200) {
          this.levelArr = res.data;
        }
      });
      if ("和平精英" == gameType) {
        gameType = "王者荣耀";
      }
      getDicts(gameType).then((res) => {
        if (res.code == 200) {
          this.regionalArr = res.data;
        }
      });
    },
    correctPush(row) {
      let params = {};
      params.name = row.saleId;
      params.status = 1;
      allList(params).then((res) => {
        if (res.code == 200) {
          if (res.rows.length > 0) {
            this.configId = res.rows[0].id;
            let id = row.result.split(",id为")[1];
            // this.getConfigId(row.saleId)
            if (row.inter == "删除") {
              let configId = this.configId;
              delAcount(id, this.configId).then((res) => {
                if (res.code == 200) {
                  if (res.msg) {
                    this.$modal.msgError(res.msg);
                  } else {
                    this.$modal.msgSuccess("操作成功");
                  }
                  this.getList();
                }
              });
            }
            if (row.inter == "编辑" || row.inter == "新增") {
              let configId = this.configId;
              //1、打开编辑页面
              this.Accountopen = true;
              //2、通过id回显数据
              if ("和平精英" == row.type) {
                this.dialogGameTypeHp = true;
              } else {
                this.dialogGameType = true;
              }
              getInfo(id).then((response) => {
                this.formAccount = response.data;
                if (response.data.urlArr) {
                  this.imgFileList = response.data.urlArr;
                  this.imgShowList = JSON.parse(
                    JSON.stringify(response.data.urlArr)
                  );
                }
                this.imageUrl = this.formAccount.titleImg;
                let video = {};
                this.videoList = [];
                this.changeSpecial();
                if (response.data.videoUrl) {
                  video.name = response.data.videoName;
                  video.url = response.data.videoUrl;
                  this.videoList[0] = video;
                }
                this.title = "修改游戏账号";
                this.inter = row.inter;
              });

              //3、调用编辑接口
            } else {
              if (!this.configId) {
                this.$modal.msgError("该接口已禁用或已删除");
                return true;
              }
            }
          } else {
            this.$modal.msgError("请求失败");
          }
        }
      });
    },
    rmRecSubmit() {
      delRecNew(this.delPartId, this.delGameName)
        .then(() => {
          this.delPartId = "";
          this.rmRecVisible = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    rmRec() {
      this.delPartId = "";
      this.delGameName = "";
      this.rmRecVisible = true;
    },
    showReq(row) {
      this.showSinNumVisible = true;
      this.req = row.req;
    },
    showRes(row) {
      this.showSinNumVisible = true;
      this.req = row.res;
    },
    allSale() {
      allList({
        channelType: 1,
      }).then((res) => {
        if (res.code == 200) {
          this.saleList = res.rows;
        }
      });
    },
    /** 查询推送记录列表 */
    getList() {
      this.loading = true;

      listRec(this.queryParams).then((response) => {
        this.recList = response.rows;
        // this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    accountCancel() {
      this.Accountopen = false;
      this.resetForm("formAccount");
      this.formAccount = {};
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        createId: null,
        saleId: null,
        result: null,
        strCode: null,
        isSucess: null,
        inter: null,
        createTime: null,
        salecode: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加推送记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getRec(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改推送记录";
      });
    },
    /** 提交按钮 */
    // submitForm() {
    //   this.$refs["form"].validate(valid => {
    //     if (valid) {
    //       if (this.form.id != null) {
    //         updateRec(this.form).then(response => {
    //           this.$modal.msgSuccess("修改成功");
    //           this.open = false;
    //           this.getList();
    //         });
    //       } else {
    //         addRec(this.form).then(response => {
    //           this.$modal.msgSuccess("新增成功");
    //           this.open = false;
    //           this.getList();
    //         });
    //       }
    //     }
    //   });
    // },
  },
};
</script>
<style lang="css" scoped>
.tip {
  color: red;
  font-size: 15px;
  margin-top: 10px;
}
</style>